package com.wkky.mechanismscreenings.listener;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.alibaba.excel.util.ListUtils;
import com.alibaba.fastjson.JSON;
import com.wkky.mechanismscreenings.entity.Staff;
import com.wkky.mechanismscreenings.service.StaffService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Slf4j
@Component
@Scope("prototype")
public class StaffListener extends AnalysisEventListener<Staff> {
    @Autowired
    @Lazy
    private StaffService staffService;

    private static final int BATCH_COUNT = 100;

    private List<Staff> importExcelDataList = ListUtils.newArrayListWithExpectedSize(BATCH_COUNT);

    //监听器，每读一行便会调用一次该监听器的方法
    @Override
    public void invoke(Staff staff, AnalysisContext analysisContext) {
      log.info("解析到一条数据：{}", JSON.toJSON(staff));
      if(staff.getStaffNum() == null){
          return;
      }
      importExcelDataList.add(staff);
      //达到100条数据，便开始去存储一次数据库
        if(importExcelDataList.size() >= BATCH_COUNT){
            saveData();
            //清空缓存
            importExcelDataList = ListUtils.newArrayListWithExpectedSize(BATCH_COUNT);
        }
    }

    private void saveData() {
        log.info("{}条数据，开始存储数据库",importExcelDataList.size());
        staffService.saveBatch(importExcelDataList);
        //清空缓存
        importExcelDataList = ListUtils.newArrayListWithExpectedSize(BATCH_COUNT);
        log.info("存储数据库成功！");
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {
        saveData();
        log.info("所有数据解析完成");

    }
}
